const bookModel = require("../../db/models")["goods"];
const responseCode = require("../../config/httpCode");
const { Op } = require("sequelize");
const router = require("koa-router")({
  prefix: "/api/goods"
});

// 添加
router.post("/", async ctx => {
  const book = ctx.request.body;
  book.view = 0;
  const b = await bookModel.create(book);
  ctx.body = {
    code: 200,
    data: b
  };
});

// 更新
router.post("/:id", async ctx => {
  const id = ctx.params.id;
  const u = ctx.request.body;
  const book = await bookModel.update(u, {
    where: {
      id
    }
  });
  ctx.body = {
    code: 200,
    data: book
  };
});

// 删除
router.delete("/:id", async ctx => {
  const id = ctx.params.id;
  await bookModel.destroy({
    where: {
      id
    }
  });
  ctx.body = {
    code: 200
  };
});

// 根据类别查询书
router.get("/", async ctx => {
  const { type, page } = ctx.query;
  const where = type ? { type } : {};
  const bk = await bookModel.findAndCountAll({});
  const books = await bookModel.findAll({
    where: where,
    limit: 10,
    offset: page ? (page - 1) * 10 : 0
  });
  ctx.body = {
    code: 200,
    data: {
      list: books,
      total: bk.count
    }
  };
});

// 模糊搜索
router.get("/search", async ctx => {
  const key = ctx.query.key;
  const search = key
    ? {
        [Op.or]: {
          title: {
            [Op.like]: `%${key}%`
          },
          desc: {
            [Op.like]: `%${key}%`
          }
        }
      }
    : {};
  const books = await bookModel.findAndCountAll({ where: search });
  ctx.body = {
    code: 200,
    data: {
      list: books.rows,
      total: books.count
    }
  };
});
// 获取热门书
router.get("/new", async ctx => {
  const bookes = await bookModel.findAll({
    order: ["view", "ASC"]
  });
});

// 获取一本书的信息
router.get("/:id", async ctx => {
  const id = ctx.params.id;
  const book = await bookModel.findOne({
    where: { id }
  });
  console.log(id, book);
  if (book) {
    await bookModel.update(
      {
        view: book.view + 1
      },
      {
        where: {
          id
        }
      }
    );
    book.view = book.view + 1;
    ctx.body = {
      code: 200,
      data: book
    };
  } else {
    throw responseCode.NOT_FOND;
  }
});

module.exports = router;
